import pigStockTakingApi from '../../../common/api/cbs/pigstocktaking.api.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { uploadFile, requestFilePath, publicFileDraw } from "../../../common/api/file-request.js";
import { Select2Info, Select2Page } from "../../../common/serve-request.js";
import { locationService } from '../../../common/locationService.js';

let _vm
(function (window, document, $) {
    $(function () {
        _vm = new Vue({
            el: "#addsaleorders-form",
            data() {
                return {
                    breedBatch: {
                        id: "",
                        name: "",
                    },
                    fiOrg: {
                        id: "",
                        name: "",
                    },
                    farmOrg: {
                        id: "",
                        name: "",
                    },
                    sType: '',
                    bizDate: moment(new Date()).format('YYYY-MM-DD'),
                    supervisorId: '',
                    supervisorName: '',
                    results: {
                        count: '',
                        profitCount: '',
                        lossCount: '',
                        avgWeight: '',
                    },
                    feedDays: '',
                    breedBatchCount: '',
                    executor: {
                        id: '',
                        name: '',
                        numCode: ''
                    },
                    remark: '',
                    uploadCount: 0,
                    attaches: [],
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                let ids = Utils.GetSessionStorage("ids")
                if (params.id || ids) {
                    document.title = '盘点记录 - 编辑'
                }
            },

        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        clickFun()
        _initCommand()
        uploadInit();
    });

    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (!isMobile() && files.length > 0) {
                    $.toptip('请使用手机拍照上传！', 'warning');
                    return false;
                }
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: async function () {
                const file = this;
                let suffix = this.name.split('.').pop().toLowerCase(); //截取附件后缀
                let name = this.name.slice(0, 11 - (suffix.length) - 1); //计算截取文件的11位字符
                let newName = name + '.' + suffix
                let file1 = publicFileDraw(newName, _vm);
                // 在这里添加日期和地点水印
                const currentDate = moment(new Date()).format('YYYY-MM-DD')
                const currentTime = moment(new Date()).format('HH:mm:ss')
                const locationWatermark = $('#addressInfo').text()
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const image = new Image();
                image.src = window.URL.createObjectURL(file);

                if (!Utils.IsNotNull(locationWatermark)) {
                    $.toptip('定位失败!', 'warning');
                    $.hideLoading();
                    $('#uploaderFiles').last().empty()
                    return
                }
                image.onload = function () {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    // 在canvas上绘制原始图片
                    context.drawImage(image, 0, 0);

                    // 添加水印，支持换行
                    const watermarkText = currentDate + ' ' + currentTime + '\n' + locationWatermark;
                    context.font = '700 ' + 80 + 'px Arial';
                    context.fillStyle = 'white';

                    // 在指定位置绘制文本
                    const x = 10;
                    const y = image.height - 160;
                    drawWrappedText(context, watermarkText, x, y, 200, 130);  // 调用自定义函数

                    // 将canvas转为Blob
                    canvas.toBlob(function (blob) {
                        const formData = new FormData();
                        formData.append('apiobjfile', blob, file1);
                        _uploadFileDraw(formData, file, _vm);
                    }, file.type || 'image/png');  // 使用原始图片的类型或默认为PNG
                }
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.attaches = _vm.attaches.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }
    // 自定义函数，用于在Canvas上绘制换行的文本
    function drawWrappedText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('\n');
        var line = '';
        var yOffset = 0;

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            var testLine = line + word + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                context.fillText(line, x, y + yOffset);
                line = word + ' ';
                yOffset += lineHeight;
            } else {
                line = testLine;
            }
        }

        context.fillText(line, x, y + yOffset);
    }
    function isMobile() {
        return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    }
    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(async res => {
            if (res.isSucceed) {
                let imageurl = await requestFilePath(res.data)
                let _list = _vm.attaches;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: imageurl.data,
                });
                _vm.attaches = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.attaches[i].id);
                    $(this).attr('data-image-id', _vm.attaches[i].imageId);
                    $(this).attr('data-url', _vm.attaches[i].url);
                    $(this).css({ 'background-image': `url(${_vm.attaches[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }
    // 编辑回显
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i].imageId).then(_res => {
                    _vm.attaches.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i].imageId,
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i].imageId}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.uploadCount = _sun;
        }
    }

    // 初始化数据
    const _initCommand = async () => {
        // 选择日期
        $('#search-date').on('click', function () {
            pick();
        });

        // 初始化 盘点类型
        let type = await requestDict(DictionaryType.PIGSTOCK_TYPE)
        let remedyDate = type.data;
        $('#sType').empty().select2({
            placeholder: '请选择盘点类型...', //默认文字提示
            language: "zh-CN", //汉化
            allowClear: true, //允许清空
            data: remedyDate.map(item => {
                return {
                    id: item.value,
                    text: item.displayName,
                }
            }),
        });
        let pigDefault = remedyDate.filter(item => {
            return item.isDefault == true
        })
        $(`#sType`).val(pigDefault[0]?.value).trigger("change")
        _vm.sType = pigDefault[0]?.value

        //选择 盘点类型
        $('#sType').on("select2:select", function () {
            _vm.sType = $('#sType').select2('data')[0]?.id
        });

        //获取养殖批次
        Select2Info($(`#breedBatch`), `${Utils.CurDomain.BaseCfgUrl}/breedbatchs/cur`, (params) => {
            return JSON.stringify({
                searchInfo: params.term,
                tags: ""
            })
        }, "POST", {
            allowClear: true,//允许清空
            placeholder: '请选择养殖批次...', //默认文字提示
            templateResult: function (res) {
                return `${res.name}`;
            }
        });
        $('#breedBatch').setSelectValue();

        // 选择批次
        $('#breedBatch').on("select2:select", async function () {
            //查询存栏数
            let quantity = await pigStockTakingApi.postBreedbatchsNum({ "id": $(this).val(), "bizDate": _vm.bizDate });
            //饲喂日龄=盘点日期-存栏日期+1
            if (Utils.IsNotNull(quantity.firstDate)) {
                let firstDate = moment(new Date(quantity.firstDate)).format('YYYY-MM-DD');
                let feedDays = ((new Date(_vm.bizDate.replace(/-/g, '/')) - new Date(firstDate.replace(/-/g, '/'))) / (1000 * 60 * 60 * 24)) + 1;
                _vm.feedDays = feedDays
            } else {
                _vm.feedDays = ''
            }
            _vm.breedBatchCount = quantity?.totalNum
            let res = Number(_vm.results.count) - Number(_vm.breedBatchCount);
            if (res > 0) { //盘盈
                _vm.results.lossCount = 0
                _vm.results.profitCount = res
            } else if (res == 0) {
                _vm.results.lossCount = 0
                _vm.results.profitCount = 0
            } else {
                _vm.results.lossCount = res.toString().slice(1)
                _vm.results.profitCount = 0
            }
            if (!Utils.IsNotNull(_vm.results.count)) {
                _vm.results.lossCount = 0
                _vm.results.profitCount = 0
            }
            $('#profitCountShow').val(Utils.toThousands(_vm.results.profitCount, 0))
            $('#lossCountShow').val(Utils.toThousands(_vm.results.lossCount, 0))
            let breedBatchInfo = $('#breedBatch').select2('data')[0]
            _vm.breedBatch.id = breedBatchInfo.id
            _vm.breedBatch.name = breedBatchInfo.name
            _vm.fiOrg.id = breedBatchInfo.fiOrgId
            _vm.fiOrg.name = breedBatchInfo.fiOrgName
            _vm.farmOrg.id = breedBatchInfo.farmOrgId
            _vm.farmOrg.name = breedBatchInfo.farmOrgName
        });
        // 输入盘点数量
        $(`#count`).on('change', function () {
            let res = Number(_vm.results.count) - Number(_vm.breedBatchCount);
            if (res > 0) { //盘盈
                _vm.results.lossCount = 0
                _vm.results.profitCount = res
            } else if (res == 0) {
                _vm.results.lossCount = 0
                _vm.results.profitCount = 0
            } else {
                _vm.results.lossCount = res.toString().slice(1)
                _vm.results.profitCount = 0
            }
            if (!Utils.IsNotNull(_vm.results.count)) {
                _vm.results.lossCount = 0
                _vm.results.profitCount = 0
            }
            $('#profitCountShow').val(Utils.toThousands(_vm.results.profitCount, 0))
            $('#lossCountShow').val(Utils.toThousands(_vm.results.lossCount, 0))
        });
        // 执行人
        Select2Page($(`#executor`), `${Utils.CurDomain.EmployeeMgtUrl}/emplrecds/by/q`, (params) => {
            return {
                searchInfo: params.term,
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            }
        }, "GET", {
            placeholder: '请选择执行人...', //默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            templateResult: function (res) {
                return `${res.name}(${res.numCode})`
            }
        });
        $(`#executor`).setSelectValue();
        //选择执行人
        $('#executor').on("select2:select", async function () {
            let executorInfo = $('#executor').select2('data')[0]
            _vm.executor = {
                id: executorInfo.id,
                name: executorInfo.name,
                numCode: executorInfo.numCode
            }
        })

        // 监督人
        Select2Page($(`#supervisor`), `${Utils.CurDomain.EmployeeMgtUrl}/emplrecds/by/q`, (params) => {
            return {
                searchInfo: params.term,
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            }
        }, "GET", {
            placeholder: '请选择监督人...', //默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            templateResult: function (res) {
                return `${res.name}(${res.numCode})`
            }
        });
        $(`#supervisor`).setSelectValue();

        //选择监督人
        $('#supervisor').on("select2:select", async function () {
            let supervisorInfo = $('#supervisor').select2('data')[0]
            _vm.supervisorId = supervisorInfo.id
            _vm.supervisorName = supervisorInfo.name
        })

        // 编辑
        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            $("#informationSubmit").text("保存");
            await pigStockTakingApi.getPigStockTaking(ids).then(res => {
                $('#breedBatch').setSelectValue(res.breedBatch.id, res.breedBatch.name);
                $('#executor').setSelectValue(res.executor.id, res.executor.name);
                $('#supervisor').setSelectValue(res.supervisorId, res.supervisorName);
                $(`#sType`).val(res.sType).trigger("change")
                _vm.breedBatch = res.breedBatch
                _vm.fiOrg = res.fiOrg
                _vm.farmOrg = res.farmOrg
                _vm.bizDate = moment(res.bizFormObj?.bizDate).format('YYYY-MM-DD')
                _vm.remark = res.remark
                _vm.sType = res.sType
                _vm.supervisorId = res.supervisorId
                _vm.supervisorName = res.supervisorName
                _vm.results = res.results
                _vm.feedDays = res.breedBatch.feedDays
                _vm.breedBatchCount = res.breedBatch.count
                _vm.executor = res.executor
                $('#profitCountShow').val(Utils.toThousands(_vm.results.profitCount, 0))
                $('#lossCountShow').val(Utils.toThousands(_vm.results.lossCount, 0))
                let editImage = []
                if (Utils.IsNotNull(res.attaches)) {
                    res.attaches.split(',').forEach(item => {
                        editImage.push({
                            "imageId": item
                        })
                    })
                    _images(editImage)
                    _vm.uploadCount = res.attaches.split(',').length
                }
            });
        }
    }
    // 时间选择器
    const pick = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                // _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
                _vm.bizDate = result.map(item => item.value).join('-');
                if (Utils.IsNotNull(_vm.breedBatch.id)) {
                    //查询存栏数
                    let quantity = await pigStockTakingApi.postBreedbatchsNum({ "id": _vm.breedBatch.id, "bizDate": _vm.bizDate });
                    //饲喂日龄=盘点日期-存栏日期+1
                    if (Utils.IsNotNull(quantity.firstDate)) {
                        let firstDate = moment(new Date(quantity.firstDate)).format('YYYY-MM-DD');
                        let feedDays = ((new Date(_vm.bizDate.replace(/-/g, '/')) - new Date(firstDate.replace(/-/g, '/'))) / (1000 * 60 * 60 * 24)) + 1;
                        _vm.feedDays = feedDays
                    } else {
                        _vm.feedDays = ''
                    }
                    _vm.breedBatchCount = quantity?.totalNum
                    let res = Number(_vm.results.count) - Number(_vm.breedBatchCount);
                    if (res > 0) { //盘盈
                        _vm.results.lossCount = 0
                        _vm.results.profitCount = res
                    } else if (res == 0) {
                        _vm.results.lossCount = 0
                        _vm.results.profitCount = 0
                    } else {
                        _vm.results.lossCount = res.toString().slice(1)
                        _vm.results.profitCount = 0
                    }
                    if (!Utils.IsNotNull(_vm.results.count)) {
                        _vm.results.lossCount = 0
                        _vm.results.profitCount = 0
                    }
                    $('#profitCountShow').val(Utils.toThousands(_vm.results.profitCount, 0))
                    $('#lossCountShow').val(Utils.toThousands(_vm.results.lossCount, 0))
                }
            }
        });// 默认配置
    }
    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../pigstocktaking/pigstocktakinglist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            if (!Utils.IsNotNull(_vm.breedBatch.id)) {
                return $.toptip(`请选择养殖批次!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.sType)) {
                return $.toptip(`请选择盘点类型!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.executor.id)) {
                return $.toptip(`请选择执行人!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.supervisorId)) {
                return $.toptip(`请选择监督人!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.results.count)) {
                return $.toptip(`请输入盘点数量!`, 'warning');
            }
            if (!(/(^[1-9]\d*$)/.test(_vm.results.count))) {
                return $.toptip(`盘点数量必须为大于0的整数!`, 'warning');
            }
            if (_vm.breedBatchCount == 0) {
                return $.toptip('该批次存栏数量为0,无法做盘点记录！', 'error')
            }
            savetips();
        })
    }
    // 保存
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;"><div class="addentry" >是否确认保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        let ids = getUrlKey("id")

                        let imageArr = []
                        _vm.attaches.forEach(item => {
                            imageArr.push(item.imageId)
                        })
                        let attachesStr = imageArr.join(',')
                        let resultsJson = {
                            count: _vm.results.count || 0,
                            profitCount: _vm.results.profitCount || 0,
                            lossCount: _vm.results.lossCount || 0,
                            avgWeight: _vm.results.avgWeight || 0,
                        }
                        let datas = {
                            ...{ breedBatch: _vm.breedBatch }, ...{ fiOrg: _vm.fiOrg }, ...{ farmOrg: _vm.farmOrg }, ...{ results: resultsJson }, ...{ executor: _vm.executor }, bizDate: _vm.bizDate, remark: _vm.remark, feedDays: _vm.feedDays || 0, breedBatchCount: _vm.breedBatchCount, attaches: attachesStr, sType: _vm.sType, supervisorName: _vm.supervisorName, supervisorId: _vm.supervisorId,
                        };
                        if (Utils.IsNotNull(ids)) {
                            return pigStockTakingApi.putPigStockTaking(ids, JSON.stringify(datas)).then(res => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示 
                                setTimeout(function () {
                                    location.href = `../pigstocktaking/pigstocktakinglist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            })
                        }
                        else {
                            pigStockTakingApi.postpigStockTaking(JSON.stringify(datas)).then(res => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示 
                                setTimeout(function () {
                                    location.href = `../pigstocktaking/pigstocktakinglist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                    }
                }
            ]
        });
    }

    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
})(window, document, jQuery)